﻿// This source is subject to Microsoft Public License (Ms-PL).
// Please see http://taskcardcreator.codeplex.com for details.
// All other rights reserved.

using System;
using System.Windows;
using System.Windows.Controls;

namespace ReportingFramework
{
  public class Repeater : WrapPanel
  {
    public Repeater()
    {
    }

    public bool TryAdd(FrameworkElement control)
    {
      // There will always be room for first control
      if (Children.Count == 0)
      {
        control.Measure(new Size(Width, Height));
        Children.Add(control);
        return true;
      }

      // Find maximum control size
      var maxHeight =  0.0;
      var maxWidth = 0.0;
      foreach (FrameworkElement child in Children)
      {
        if (child.DesiredSize.Height > maxHeight)
          maxHeight = child.DesiredSize.Height;
        if (child.DesiredSize.Width > maxWidth)
          maxWidth = child.DesiredSize.Width;
      }

      // Is there room left?
      var columns = (int) Math.Truncate(Width/maxWidth);
      var rows = (int) Math.Truncate(Height/maxHeight);
      if (Children.Count >= columns*rows)
      {
        return false;
      }

      control.Measure(new Size(Width, Height));
      Children.Add(control);
      return true;
    }
  }
}
